﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Serious
{
    public class CylinderInputHandler
    {
        private Index2 prev_vecdir, vecdir;
        private int prev_turn_signal, turn_signal;
        private bool jump;
        private bool fall;

        private void reset ()
        {
            prev_vecdir = vecdir = Index2.Zero;
            prev_turn_signal = turn_signal = 0;
            jump = false;
            fall = false;
        }

        public CylinderInputHandler()
        {
            reset();
        }

        public void HandleKeyboardEvent (KeyboardEvent kev)
        {
            Index2 vd = Index2.Zero;
            if (kev.IsKeyDown(Keys.W)) vd.X += 1;
            if (kev.IsKeyDown(Keys.S)) vd.X -= 1;
            if (kev.IsKeyDown(Keys.A)) vd.Y += 1;
            if (kev.IsKeyDown(Keys.D)) vd.Y -= 1;
            vecdir = vd;

            int ts = 0;
            if (kev.IsKeyDown(Keys.Left)) ts += 1;
            if (kev.IsKeyDown(Keys.Right)) ts -= 1;
            turn_signal = ts;

            if (kev.WasKeyPressed(Keys.Up) || kev.WasKeyPressed(Keys.Space)) jump = true;

            if (kev.WasKeyPressed(Keys.Down)) fall = true;
        }

        public void Apply(CylinderControllerBasic cc)
        {
            if (vecdir != prev_vecdir)
            {
                if (vecdir)
                {
                    cc.StartMovingInDirection(Vector2.Normalize((Vector2)vecdir));
                }
                else
                {
                    cc.StopMoving();
                }
            }

            if (turn_signal != prev_turn_signal)
            {
                switch (turn_signal)
                {
                    case 1:
                        cc.StartTurningLeft();
                        break;

                    case -1:
                        cc.StartTurningRight();
                        break;

                    case 0:
                        cc.StopTurning();
                        break;
                }
            }

            if (jump)
            {
                cc.Jump();
            }

            if (fall)
            {
                cc.FastFall();
            }

            prev_vecdir = vecdir;
            prev_turn_signal = turn_signal;
            jump = false;
            fall = false;
        }
    }
}
